from H3DInterface import *
import random, string, os

#This has to be global so that it can be used by the python module that handles the pen.
globals()["width"] = 0.05
globals()["rotationSpeed"] = 0.0015
globals()["grasp"] = False
globals()["imageCount"] = 0

texture = createX3DNodeFromString( "<ImageTexture url=\"MMI.png\"/>")[0]
textures = []
textures.append(texture)
texture = createX3DNodeFromString( "<ImageTexture url=\"MMI_landuse_hillshade.png\"/>")[0]
textures.append(texture)
texture = createX3DNodeFromString( "<ImageTexture url=\"MMI_DRG_100K_hillshade.png\"/>")[0]
textures.append(texture)

deform_node, = references.getValue()
appearance = deform_node.appearance.getValue()

#Handles the spaceware mouse button press
class swPressed( AutoUpdate( SFInt32 ) ):
    def update(self, event):
        button = event.getValue()
        if button == 11: #The white button right of the puck.
            globals()["width"] = globals()["width"] + 0.01
        elif button == 10: #The white button left of the puck.
            globals()["width"] = globals()["width"] - 0.01
        elif button == 1:
            globals()["rotationSpeed"] -= 0.0005
        elif button == 2:
            globals()["rotationSpeed"] += 0.0005
        elif button == 3:
            globals()["grasp"] = not globals()["grasp"]
            file = open("C:/temp/grasp.txt", "w")
            file.write(str(int(globals()["grasp"])))
            file.close()
        elif button == 4:
            globals()["imageCount"] += 1
            if globals()["imageCount"] >= 3:
                globals()["imageCount"] = 0
            appearance.texture.setValue(textures[globals()["imageCount"]])
        elif button == 5:
            its.shouldCut.setValue(0)
            deform_node.shouldDeform.setValue(1)
        elif button == 6:
            its.shouldCut.setValue(1)
            deform_node.shouldDeform.setValue(0)
        return 1 #we have to return something, but it really doesn't matter to us what.
        
swButton = swPressed()

class getWidth( TypedField( SFFloat, SFTime) ):
    def update(self, event):
        return globals()["width"]

myWidth = getWidth()
time.route( myWidth )

class getRotation( TypedField( SFFloat, SFTime) ):
    def update(self,event):
        return globals()["rotationSpeed"]

changeRotation = getRotation()
time.route(changeRotation)

class setGrasp( AutoUpdate(SFBool) ):
    def update(self,event):
        return globals()["grasp"] and event.getValue()

graspMe = setGrasp()

##class Transform( TypedField( SFVec3f,(SFMatrix4f, SFVec3f ) ) ):
##  def update( self, event ):
##      global inverseMatrix, transformMat, penPos
##      routes_in = self.getRoutesIn()
##      inverseMatrix = routes_in[0].getValue()
##      penPos = routes_in[1].getValue()
##      transformMat = inverseMatrix.getRotationPart()
##      print transformMat * penPos
##      return transformMat * penPos
##
##trans = Transform()

##class convertTracker(TypedField(SFVec3f, SFTime)):
##    def update(self,event):
##        proxy
##
##newTracker = convertTracker()
##time.route(newTracker)

##class Gaussian( TypedField( SFFloat, SFTime ) ):
##  def update( self, event ):
##    global fric
##    fric = random.gauss( .3 , 0.3)
##    #avoids invalid data--value must be positive and less than 1
##    if fric > 1:
##        fric = fric/2
##    return abs(fric)
##
##gauss = Gaussian()
##time.route( gauss )

# This python file creates an rectangular IndexedTriangleSet with
# columns X rows coordinates.
columns = 10
rows = 10
size = Vec2f( 0.4, 0.4 )

coords = []
tex_coords = []
index = []


step_c = size.x / columns
step_r = size.y / rows

tc_step_c = 1.0/ columns
tc_step_r = 1.0/ rows

##myFile = open('E:/H3D/H3DAPI/examples/DeformableShape/MMI2.pgm', 'r')
##line = myFile.readline()
##line = myFile.readline()
##line = myFile.readline()

for c in range( columns ):
  for r in range( rows ):
      coords.append( Vec3f( step_c * c - size.x / 2, step_r * r - size.x/2,0))##float(myFile.readline())/3000))
      tex_coords.append( Vec2f( tc_step_c * c, tc_step_r * r ) )
##    red = myFile.readline()
##    g = myFile.readline()
##    b = myFile.readline()
##    if float(red.strip("\n")) > 200 and (float(b.strip("\n"))) < 135 and (float(g.strip("\n"))) > 120 :
##        coords.append( Vec3f( step_c * c - size.x / 2, step_r * r - size.x/2, (((float(red.strip("\n"))* 3) + (float(g.strip("\n")) * 2) + float(b.strip("\n")))/9000) ))
##    elif (float(b.strip("\n"))) < 1500:
##        coords.append( Vec3f( step_c * c - size.x / 2, step_r * r - size.x/2, (((float(red.strip("\n"))* 2) + (float(g.strip("\n")) * 2) + float(b.strip("\n")))/9000) ))
##    else:
##        coords.append( Vec3f( step_c * c - size.x / 2, step_r * r - size.x/2, (((float( red.strip("\n") )) + (float(g.strip("\n"))) + float(b.strip("\n")))/9000) ))

for c in range( columns - 1 ):
  for r in range( rows - 1 ):
    v0 = r * columns + c 
    v1 = r * columns + c+1
    v2 = (r+1) * columns + c+1
    v3 = (r+1) * columns + c
    index = index + [v0, v1, v2, v0, v2, v3 ]

##deform_node.appearance.textureNode.setValue( textures[1] )

its =  createX3DNodeFromString( "<GeoCuttableSurface solid=\"FALSE\" containerField=\"hapticGeometry\" shouldCut=\"true\" />" )[0]

##myFile = open('E:/H3D/H3DAPI/examples/DeformableShape/log.txt', 'w+')
##for count in range(0, len(index)):
##    myFile.write(str(index[count]))
##    if ((count+1)%3)!=0:
##        myFile.write(" ")
##    else:
##        myFile.write("\n")
##myFile.close()

coord = createX3DNodeFromString( "<Coordinate />" )[0]
coord.point.setValue( coords )

##These two need to be commented out normally
##tex_coord = createX3DNodeFromString( "<TextureCoordinate />" )[0]
##tex_coord.point.setValue( tex_coords )

its.index.setValue( index )
its.coord.setValue( coord )

#This should normally be commented out
##its.texCoord.setValue( tex_coord )

deform_node.geometry.setValue( its )




